package com.store.utils;

import com.alibaba.fastjson.JSON;
import com.store.model.config.ApplicationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

@Component
public class ExpressUtil {

    @Autowired
    private ApplicationEntity entity;

    private static final String devId = "dev_id";
    private static final String devKey = "dev_key";

    public String sort(Object obj){
        Map<String,Object> jsonMap = beanToMap(obj);
        sortMapByKey(jsonMap);
        return JSON.toJSONString(jsonMap);
    }

    public Map<String,Object> beanToMap(Object obj){
        String jsonStr = JSON.toJSONString(obj);
        return JSON.parseObject(jsonStr);
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String,Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    public String sign(String content) {
        try {
            String toSign = content + "&" + entity.getSf().get(devId) + "&" + entity.getSf().get(devKey);
            System.out.println(toSign);
            String md5Result = EncryptUtils.md5(toSign.getBytes("utf-8").toString());
            String signResult = base64Encode(md5Result.getBytes("utf-8"));
            return signResult;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected String base64Encode(byte[] md5ResultBytes) {
        java.util.Base64.Encoder be = java.util.Base64.getEncoder();
        String b64Result = be.encodeToString(md5ResultBytes);
        return b64Result;
    }
}

class MapKeyComparator implements Comparator<String> {

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }
}